//
//  HSListDetailVC.m
//  HolyShit
//
//  Created by Robin on 2017/3/24.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "HSListDetailVC.h"
#import "HSListDetailVM.h"
#import "NSMutableAttributedString+HSFeedDetail.h"
#import "NSString+Html.h"
#import "HSWebVC.h"
#import "HSLoginVC.h"

@interface HSListDetailVC ()

@property (nonatomic, strong) HSListDetailVM *detailVM;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel *titleLb;
@property (nonatomic, strong) UIImageView *iconImgV;
@property (nonatomic, strong) UILabel *sourceLb;
@property (nonatomic, strong) UILabel *timeLb;
@property (nonatomic, strong) YYLabel *contentLb;
@property (nonatomic, strong) HSListModel *model;
@property (nonatomic, strong) NSMutableArray<HSListModel *> *datas;
@property (nonatomic, assign) BOOL isCollected;

@end

@implementation HSListDetailVC

- (instancetype)initWithModel:(HSListModel *)model
{
    if (self = [super init]) {
        _detailVM = [[HSListDetailVM alloc] initWithPostId:model.postid];
        _model = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self rightTitleWithTitle:@"更多"];
    [self commonInit];
    @weakify(self);
    [self.hintView setReloadBlock:^{
        @strongify(self);
        self.hintView.hintState = MYHintStateLoading;
        [self requestData];
    }];
    self.hintView.reloadBlock();
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if([[NSUserDefaults standardUserDefaults] objectForKey:userNameKey]){
        NSArray *data = [[MYCacheHelper shareHelper] my_cacheWithKey:collectionKey clazz:[NSArray class]];
        if (data && data.count > 0) {
            self.datas = data.mutableCopy;
            [self.datas enumerateObjectsUsingBlock:^(HSListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if([obj.postid isEqualToString:self.model.postid]){
                    self.isCollected = YES;
                    *stop = YES;
                }
            }];
        }
        else{
            self.datas = @[].mutableCopy;
        }
    }
}

- (void)commonInit
{
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.height.mas_equalTo(ScreenHeight - NavBarHeight);
        make.width.mas_equalTo(ScreenWidth);
    }];
    
    [self.scrollView addSubview:self.titleLb];
    [self.titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(10);
        make.width.mas_equalTo(ScreenWidth - 20);
    }];
    
    [self.scrollView addSubview:self.timeLb];
    [self.timeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.equalTo(self.titleLb.mas_bottom).offset(10);
    }];
    
    [self.scrollView addSubview:self.contentLb];
    [self.contentLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.titleLb);
        make.top.equalTo(self.timeLb.mas_bottom).offset(10);
    }];
    
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contentLb.mas_bottom);
    }];
}

- (void)updateUI
{
    self.titleLb.text = self.detailVM.detailModel.title;
    NSDate *date = [NSDate dateWithString:self.detailVM.detailModel.ptime format:@"yyyy-MM-dd HH:mm:ss"];
    self.timeLb.text = [date stringWithFormat:@"MM-dd HH:mm"];
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:self.detailVM.detailModel.body];
    text.font = MYFont(Font36);
    text.lineBreakMode = NSLineBreakByWordWrapping;
    text.color = HEXCOLOR(HSColorBlack);
    text.lineSpacing = 8;
    [text replaceHtmlTag];
    
    YYTextLayout *layout = [YYTextLayout layoutWithContainer:[YYTextContainer containerWithSize:CGSizeMake(ScreenWidth - 20, CGFLOAT_MAX)] text:text];
    self.contentLb.textLayout = layout;
}

- (void)requestData
{
    @weakify(self);
    [[self.detailVM.dataCommand execute:nil] subscribeNext:^(id x) {
        @strongify(self);
        self.hintView.hintState = MYHintStateHidden;
        [self updateUI];
    } error:^(NSError *error) {
        self.hintView.hintState = MYHintStateNoData;
        [UIWindow showError:error];
    }];
}

- (void)rightButtonTouch
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *share = [UIAlertAction actionWithTitle:@"分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:self.detailVM.detailModel.shareLink];
        UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:@[url] applicationActivities:nil];
        activity.excludedActivityTypes = @[UIActivityTypePostToWeibo, UIActivityTypePostToTencentWeibo, UIActivityTypePostToFacebook, UIActivityTypePostToTwitter, UIActivityTypeCopyToPasteboard, UIActivityTypeMail, UIActivityTypeMessage];
        // 分享完成
        activity.completionWithItemsHandler = ^(NSString *activityType, BOOL completed,
                                                NSArray *returnedItems, NSError *activityError) {
            
            // 分享完成或退出分享时调用该方法
            NSLog(@"分享完成");
        };
        [self presentViewController:activity animated:YES completion:NULL];
    }];
    UIAlertAction *orign = [UIAlertAction actionWithTitle:@"查看原网页" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self my_push:[[HSWebVC alloc] initWithUrl:self.detailVM.detailModel.shareLink]];
    }];
    UIAlertAction *collect = [UIAlertAction actionWithTitle:self.isCollected ? @"取消收藏" : @"收藏" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([[NSUserDefaults standardUserDefaults] objectForKey:userNameKey]){
            if (self.isCollected) {
                [self.datas enumerateObjectsUsingBlock:^(HSListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.postid isEqualToString:self.model.postid]) {
                        [self.datas removeObject:obj];
                        self.isCollected = NO;
                        *stop = YES;
                        [UIWindow showSuccessMsg:@"取消收藏成功"];
                    }
                }];
            }
            else{
                [self.datas addObject:self.model];
                self.isCollected = YES;
                [UIWindow showSuccessMsg:@"收藏成功"];
            }
            [[MYCacheHelper shareHelper] my_saveCacheWithObject:self.datas key:collectionKey];
        }
        else{
            [self my_push:[HSLoginVC new]];
        }
    }];
    [alert addAction:cancle];
    [alert addAction:share];
    [alert addAction:orign];
    [alert addAction:collect];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - getter & setter

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

- (UILabel *)titleLb
{
    if (!_titleLb) {
        _titleLb = [UILabel labelWithFont:MYFont(18) color:HEXCOLOR(HSColorBlack)];
        _titleLb.numberOfLines = 0;
    }
    return _titleLb;
}

- (UIImageView *)iconImgV
{
    if (!_iconImgV) {
        _iconImgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15) imageType:MYImageTypeSmallPic];
    }
    return _iconImgV;
}

-(UILabel *)sourceLb
{
    if (!_sourceLb) {
        _sourceLb = [UILabel labelWithFont:MYFont(Font24) color:HEXCOLOR(HSColorBlue)];
    }
    return _sourceLb;
}

- (UILabel *)timeLb
{
    if (!_timeLb) {
        _timeLb = [UILabel labelWithFont:MYFont(Font24) color:HEXCOLOR(HSColorGray)];
    }
    return _timeLb;
}

- (YYLabel *)contentLb
{
    if (!_contentLb) {
        _contentLb = [YYLabel new];
        _contentLb.numberOfLines = 0;
        _contentLb.preferredMaxLayoutWidth = ScreenWidth - 20;
        _contentLb.displaysAsynchronously = YES;
        _contentLb.ignoreCommonProperties = YES;
    }
    return _contentLb;
}

@end
